package com.subang.function.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.subang.common.core.domain.entity.SysUser;
import com.subang.common.utils.SecurityUtils;
import com.subang.framework.web.service.UserIntegralService;
import com.subang.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.subang.common.annotation.Log;
import com.subang.common.core.controller.BaseController;
import com.subang.common.core.domain.AjaxResult;
import com.subang.common.enums.BusinessType;
import com.subang.function.domain.SbAnswerRecord;
import com.subang.function.service.ISbAnswerRecordService;
import com.subang.common.utils.poi.ExcelUtil;
import com.subang.common.core.page.TableDataInfo;

/**
 * 答题记录Controller
 * 
 * @author subei
 * @date 2025-04-22
 */
@RestController
@RequestMapping("/function/record")
public class SbAnswerRecordController extends BaseController
{
    @Autowired
    private ISbAnswerRecordService sbAnswerRecordService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private UserIntegralService userIntegralService;

    /**
     * 查询答题记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbAnswerRecord sbAnswerRecord)
    {
        startPage();
        List<SbAnswerRecord> list = sbAnswerRecordService.selectSbAnswerRecordList(sbAnswerRecord);
        for(SbAnswerRecord sbAnswerRecord1 : list){
            SysUser sbAnswerRecordUser = userService.selectUserById(sbAnswerRecord1.getUserId());
            sbAnswerRecord1.setUserName(sbAnswerRecordUser.getNickName());
        }
        return getDataTable(list);
    }

    /**
     * 导出答题记录列表
     */
    @PreAuthorize("@ss.hasPermi('function:record:export')")
    @Log(title = "答题记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbAnswerRecord sbAnswerRecord)
    {
        List<SbAnswerRecord> list = sbAnswerRecordService.selectSbAnswerRecordList(sbAnswerRecord);
        ExcelUtil<SbAnswerRecord> util = new ExcelUtil<SbAnswerRecord>(SbAnswerRecord.class);
        util.exportExcel(response, list, "答题记录数据");
    }

    /**
     * 获取答题记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sbAnswerRecordService.selectSbAnswerRecordById(id));
    }

    /**
     * 新增答题记录
     */
    @Log(title = "答题记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbAnswerRecord sbAnswerRecord) {
        String modeType = sbAnswerRecord.getModeType();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        sbAnswerRecord.setUserId(user.getUserId());

        // 积分更新
        userIntegralService.updateUserIntegral("table-analysis".equals(modeType) ? "table-analysis" : "basic-calculations");

        // 如果是 basic-calculations 模式，使用基于时间的逻辑
        if ("table-analysis".equals(modeType)) {
            sbAnswerRecord.setCreateTime(new Date());

            // 查询用户相同模式类型的历史记录
            SbAnswerRecord queryRecord = new SbAnswerRecord();
            queryRecord.setUserId(user.getUserId());
            queryRecord.setModeType(sbAnswerRecord.getModeType());
            List<SbAnswerRecord> list = sbAnswerRecordService.selectSbAnswerRecordList(queryRecord);

            if (list.isEmpty()) {
                // 如果没有历史记录，执行新增操作，同时把训练模式最高分保存为训练模式总分
                sbAnswerRecord.setModeTotalPoints(sbAnswerRecord.getModeBest());
                int result = sbAnswerRecordService.insertSbAnswerRecord(sbAnswerRecord);
                if (result > 0) {
                    return AjaxResult.success("创造新记录");
                } else {
                    return AjaxResult.error("保存失败");
                }
            } else {
                // 遍历列表，找到最高分记录
                SbAnswerRecord bestRecord = list.get(0);
                for (SbAnswerRecord record : list) {
                    if (record.getModeBest() < bestRecord.getModeBest()) {
                        bestRecord = record;
                    }
                }

                boolean isNewRecord = false;
                // 如果前端传递的分数大于历史最高分，则更新最高分
                if (sbAnswerRecord.getModeBest() > bestRecord.getModeBest()) {
                    bestRecord.setModeBest(sbAnswerRecord.getModeBest());
                    bestRecord.setCreateTime(new Date());
                    isNewRecord = true;
                }

                // 不管模式最高分是否超过历史记录，记录总分等于当前总分加上模式最高分
                bestRecord.setModeTotalPoints(bestRecord.getModeTotalPoints() + sbAnswerRecord.getModeBest());

                int result = sbAnswerRecordService.updateSbAnswerRecord(bestRecord);
                if (result > 0) {
                    return isNewRecord ? AjaxResult.success("创造新记录") : AjaxResult.success("保存成功");
                } else {
                    return AjaxResult.error("保存失败");
                }
            }
        } else {
            SbAnswerRecord queryRecord = new SbAnswerRecord();
            queryRecord.setUserId(user.getUserId());
            queryRecord.setModeType(sbAnswerRecord.getModeType());
            List<SbAnswerRecord> list = sbAnswerRecordService.selectSbAnswerRecordList(queryRecord);

            if (!list.isEmpty()) {
                SbAnswerRecord bestRecord = null;
                for (SbAnswerRecord record : list) {
                    if (bestRecord == null || record.getTotalTime() < bestRecord.getTotalTime()) {
                        bestRecord = record;
                    }
                }

                if (bestRecord.getTotalTime() > sbAnswerRecord.getTotalTime()) {
                    bestRecord.setTotalTime(sbAnswerRecord.getTotalTime());
                    bestRecord.setCreateTime(new Date());
                    return toAjax(sbAnswerRecordService.updateSbAnswerRecord(bestRecord));
                } else {
                    return AjaxResult.error("成绩不好，不保存");
                }
            } else {
                return toAjax(sbAnswerRecordService.insertSbAnswerRecord(sbAnswerRecord));
            }

        }
    }

    /**
     * 修改答题记录
     */
    @PreAuthorize("@ss.hasPermi('function:record:edit')")
    @Log(title = "答题记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbAnswerRecord sbAnswerRecord)
    {
        return toAjax(sbAnswerRecordService.updateSbAnswerRecord(sbAnswerRecord));
    }

    /**
     * 删除答题记录
     */
    @PreAuthorize("@ss.hasPermi('function:record:remove')")
    @Log(title = "答题记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sbAnswerRecordService.deleteSbAnswerRecordByIds(ids));
    }
}
